﻿using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using ZXing;

namespace MicroCloud.Utils
{
    /// <summary>
    /// 二维码生成类
    /// </summary>
    public class QRCoder
    {
        /// <summary>
        /// 生成二维码图片
        /// </summary>
        /// <param name="content">存储内容</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>
        /// <returns>二维码图片</returns>
        public static Image CreateImage(string content, int width = 500, int height = 500)
        {
            var writer = new ZXing.ImageSharp.BarcodeWriter<Rgba32>
            {
                Format = BarcodeFormat.QR_CODE,
                Options = new ZXing.QrCode.QrCodeEncodingOptions
                {
                    DisableECI = true,
                    CharacterSet = "UTF-8",
                    Width = width,
                    Height = height,
                    Margin = 1
                }
            };
            var image = writer.WriteAsImageSharp<Rgba32>(content);
            //var ms = new MemoryStream();
            //image.Save(ms, new PngEncoder());
            return image;
        }

        /// <summary>
        /// 生成带logo的二维码图片
        /// </summary>
        /// <param name="content">存储内容</param>
        /// <param name="logo">logo图片</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>
        /// <param name="logoWidth">logo宽度百分比（0-1之间）</param>
        /// <param name="logoHeight">logo高度百分比（0-1之间）</param>
        /// <param name="opacity">不透明度百分比（0-1之间）</param>
        /// <param name="colorBlending">要应用的颜色混合</param>
        /// <param name="alphaComposition">像素合成</param>
        /// <returns></returns>
        public static Image CreateImage(string content, Image logo, int width = 500, int height = 500, double logoWidth = 0.2, double logoHeight = 0.2
            , float opacity = 1, PixelColorBlendingMode colorBlending = PixelColorBlendingMode.Normal, PixelAlphaCompositionMode alphaComposition = PixelAlphaCompositionMode.SrcOver)
        {
            Check.NotNull(logo, nameof(logo));

            var qrImage = CreateImage(content, width, height);
            //logo大小调整
            logo.Mutate(ctx => { ctx.Resize((int)(qrImage.Width * logoWidth), (int)(qrImage.Height * logoHeight)); });
            //在二维码上绘制图片
            qrImage.Mutate(ctx =>
            {
                ctx.DrawImage(logo, new Point(qrImage.Width / 2 - logo.Width / 2, qrImage.Height / 2 - logo.Height / 2), colorBlending, alphaComposition, opacity);
            });

            return qrImage;
        }

    }
}